package com.bluedot.www.core.utils;

import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
 * 压缩文件工具类
 * @author He Peng
 * @version 1.0
 * @date 2021/10/25 15:04
 */
public class ZipUtil {

    @Test
    public void test() {
        List<String> list = new ArrayList<>();
        list.add("bluedot/report/2021/10/23/a7427e5c265a4bda.docx");
        list.add("bluedot/report/2021/10/23/a7427e5c265a4bda.docx");
        Map<String, InputStream> fileMap = OSSManageUtil.getFileInfoFromUrlBatch(list);
        zipFiles(fileMap);
    }

    public static ByteArrayOutputStream zipFiles(Map<String, InputStream> inputStreamMap) {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream, StandardCharsets.UTF_8);
        try {
            for (Map.Entry<String, InputStream> entry : inputStreamMap.entrySet()) {
                byte[] buff = new byte[1024];
                InputStream in = entry.getValue();
                zipOutputStream.putNextEntry(new ZipEntry(entry.getKey()));
                int len = -1;
                while ((len = in.read(buff)) != -1) {
                    zipOutputStream.write(buff, 0, len);
                }
            }
            zipOutputStream.close();
        } catch(IOException e) {
            e.printStackTrace();
        }

        return byteArrayOutputStream;
    }


    /**
     * 输入流转输出流
     * @param inputStreamList: 输入流集合
     * @return java.util.List<java.io.OutputStream>
     * @author He Peng
     * @date 2021/10/25 15:28
     */
    private static List<OutputStream> inputStreamToOutputStream(List<InputStream> inputStreamList) {
        List<OutputStream> outputStreamList = new ArrayList<>();
        for (InputStream inputStream : inputStreamList) {
            OutputStream outputStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int len = 0;
            try {
                while ((len = inputStream.read(buff)) != -1) {
                    outputStream.write(buff, 0, len);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputStreamList.add(outputStream);
        }
        return outputStreamList;
    }
}
